package com.manage.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 作者：威哥
 * 时间：2021/9/27 14:02
 * 描述：永无bug
 */
public class CookieUtils {

    public static void setCookie(String name, String value,HttpServletResponse resp, HttpServletRequest request){
        setCookie(name,value,60*60*24*7,resp,request.getContextPath());
    }
    public static void setCookie(String name, String value, int maxAge, HttpServletResponse resp, HttpServletRequest request){
        setCookie(name,value,maxAge,resp,request.getContextPath());
    }
    public static void setCookie(String name, String value,String path,HttpServletResponse resp){
        setCookie(name,value,60*60*24*7,resp,path);
    }
    public static void setCookie(String name, String value, int maxAge, HttpServletResponse resp,String path){
        Cookie cookie = null;
        //1、创建Cookie
        try {
            cookie = new Cookie(URLEncoder.encode(name,"utf-8"),value);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(cookie == null) return;

        //2、设置Cookie
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);

        //3、将Cookie响应到客户端
        resp.addCookie(cookie);
    }

    public static Cookie getCookie(String name,HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies == null || cookies.length == 0)return null;
        for (Cookie cookie : cookies) {
            try {
                if(URLDecoder.decode(cookie.getName(),"utf-8").equals(name)){
                    return cookie;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void removeCookie(String name,HttpServletRequest request,HttpServletResponse response){
        //1、先查询此Cookie是否存在
        Cookie cookie = getCookie(name, request);
        if(cookie == null) return;
        //2、修改的Cookie有效时间
        cookie.setMaxAge(0);
        //3、协会到客户端浏览器
        response.addCookie(cookie);
    }
}
